package com.yunhe.inspect.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.constant.InSpectConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.authority.Organization;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.CollectionUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.inspect.client.AuthorityClient;
import com.yunhe.inspect.domain.ItemPlan;
import com.yunhe.inspect.model.ItemPlanCondition;
import com.yunhe.inspect.model.ItemPlanBO;
import com.yunhe.inspect.model.ItemPlanUnit;
import com.yunhe.inspect.repository.ItemPlanRepository;
import com.yunhe.inspect.service.ItemPlanService;
import com.yunhe.inspect.util.MyHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: ItemPlanServiceImpl
 * @Description:
 * @author: GongDaCheng
 * @Date: 10:44 2021/11/9
 */
@Service
public class ItemPlanServiceImpl implements ItemPlanService {

    @Autowired
    private ItemPlanRepository itemPlanRepository;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private AuthorityClient authorityClient;

    @Override
    public int createItemPlan (ItemPlanBO itemPlanBO) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        int sum = 0;
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        List<ItemPlanUnit> items = itemPlanBO.getItems();
        for (ItemPlanUnit item : items) {
            ItemPlan itemPlan = new ItemPlan();
            if(!StringUtil.isEmpty(projectCode)){
                itemPlan.setStationId(Long.valueOf(projectCode));
            }
            itemPlan.setCreatePerson(headerUser);
            itemPlan.setDepartment(itemPlanBO.getDepartment());
            itemPlan.setItemType(item.getItemType());
            itemPlan.setItemContent(item.getItemContent());
            itemPlan.setIsDelete("0");
            itemPlan.setOperationTime(new Date());
            int count = itemPlanRepository.createItemPlanSelective(itemPlan);
            sum += count;
        }
        return sum;
    }

    @Override
    public int deleteItemPlan(String idsStr) {
        List<Long> ids = new ArrayList<>();
        if (!StringUtil.isEmpty(idsStr)) {
            String[] split = idsStr.split(",");
            for (String s : split) {
                ids.add(Long.parseLong(s));
            }
        }
        int sum = 0;
        for (Long id : ids) {
            int count = itemPlanRepository.deleteItemPlanByPrimaryKey(id);
            sum += count;
        }
        return sum;
    }


    @Override
    public int updateItemPlan(ItemPlan itemPlan) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        itemPlan.setUpdatePerson(headerUser);
        itemPlan.setOperationTime(new Date());
        return itemPlanRepository.updateItemPlanByPrimaryKeySelective(itemPlan);
    }


    @Override
    public ItemPlan findItemPlanById(Long id) {
        ItemPlan itemPlan = itemPlanRepository.searchItemPlanByPrimaryKey(id);
        itemPlan.setItemTypeTitle(InSpectConsts.Item_Type.getTitleByValue(itemPlan.getItemType()));
        return itemPlan;
    }

    @Override
    public PageResult getItemPlanByCondition(ItemPlanCondition itemPlanCondition) throws ArgumentErrorException {
        PageResult result = null;
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(!StringUtil.isEmpty(projectCode)){
            itemPlanCondition.setStationId(Long.parseLong(projectCode));
        }
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (itemPlanCondition.getDepartment() == null){
            //查询当前登录人的部门以及负责部门和子部门
            ResponseEntity<ResultObject<List<Organization>>> responseEntity = authorityClient.getSubOrgByLoginUser(Long.valueOf(projectCode),headerUser,true);
            if(responseEntity != null){
                if(responseEntity.getStatusCode().is2xxSuccessful()){
                    List<Organization> organizations = responseEntity.getBody().getResults();
                    if(CollectionUtil.isNotEmpty(organizations)){
                        List<Long> orgIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
                        itemPlanCondition.setDepartmentIds(orgIds);
                    }
                }
            }
        }else {
            itemPlanCondition.setDepartmentIds(Arrays.asList(itemPlanCondition.getDepartment()));
        }
        PageHelper.startPage(itemPlanCondition.getPage(), itemPlanCondition.getSize());
        List<ItemPlan> itemPlanByCondition = itemPlanRepository.getItemPlanByCondition(itemPlanCondition);
        for (ItemPlan itemPlan : itemPlanByCondition) {
            itemPlan.setItemTypeTitle(InSpectConsts.Item_Type.getTitleByValue(itemPlan.getItemType()));
        }
        PageInfo<ItemPlan> pageInfo = new PageInfo<>(itemPlanByCondition);
        result = new PageResult(itemPlanCondition.getPage(), itemPlanCondition.getSize(), (int)pageInfo.getTotal(), itemPlanByCondition);
        return result;
    }

    @Override
    public List<ItemPlan> getItemPlanByOrgId(Long orgId) {
        return itemPlanRepository.getItemPlanByOrgId(orgId);
    }
}
